<template>
  <div class="receive-container">
    <!-- 管理员审核区域 -->
    <el-card v-if="isAdmin" class="audit-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">待审核申领</span>
          <el-button :icon="Refresh" circle @click="loadPendingClaims" />
        </div>
      </template>

      <div v-loading="auditLoading">
        <el-empty v-if="!auditLoading && pendingClaims.length === 0" description="暂无待审核申领" />
        
        <div v-else class="audit-list">
          <div
            v-for="claim in pendingClaims"
            :key="claim.id"
            class="audit-item"
          >
            <div class="audit-info">
              <div class="item-title">{{ claim.itemTitle }}</div>
              <div class="item-meta">
                <el-tag size="small">{{ claim.itemCategory }}</el-tag>
                <span class="location">{{ claim.itemLocation }}</span>
              </div>
              <div class="claim-info">
                <span>申领人：{{ claim.username }}</span>
                <span class="divider">|</span>
                <span>联系方式：{{ claim.contactInfo }}</span>
                <span class="divider">|</span>
                <span>申领时间：{{ formatTime(claim.createTime) }}</span>
              </div>
              <div class="claim-reason">申领理由：{{ claim.reason }}</div>
            </div>
            <div class="audit-actions">
              <el-button type="success" size="small" @click="handleAudit(claim.id, 1)">
                通过
              </el-button>
              <el-button type="danger" size="small" @click="handleReject(claim.id)">
                驳回
              </el-button>
            </div>
          </div>
        </div>

        <el-pagination
          v-if="pendingClaims.length > 0"
          v-model:current-page="auditPage"
          v-model:page-size="auditPageSize"
          :total="auditTotal"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next"
          class="pagination"
          @size-change="loadPendingClaims"
          @current-change="loadPendingClaims"
        />
      </div>
    </el-card>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="queryParams.keyword"
            placeholder="搜索标题或描述"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="物品类别">
          <el-select
            v-model="queryParams.category"
            placeholder="全部类别"
            clearable
            @change="handleSearch"
          >
            <el-option label="电子产品" value="电子产品" />
            <el-option label="证件卡类" value="证件卡类" />
            <el-option label="书籍资料" value="书籍资料" />
            <el-option label="生活用品" value="生活用品" />
            <el-option label="钥匙" value="钥匙" />
            <el-option label="衣物饰品" value="衣物饰品" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="queryParams.status"
            placeholder="全部状态"
            clearable
            @change="handleSearch"
          >
            <el-option label="待认领" :value="0" />
            <el-option label="已申领" :value="1" />
            <el-option label="已归还" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 失物列表 -->
    <div v-loading="loading" class="list-container">
      <el-empty v-if="!loading && lostItemList.length === 0" description="暂无失物信息" />
      
      <el-row :gutter="20" v-else>
        <el-col
          v-for="item in lostItemList"
          :key="item.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card class="item-card" shadow="hover">
            <!-- 图片 -->
            <div class="item-image" @click="handleViewDetail(item)">
              <el-image
                :src="item.images[0]"
                fit="cover"
                :preview-src-list="[]"
                :preview-teleported="false"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <el-tag
                :type="getStatusType(item.status)"
                class="status-tag"
              >
                {{ getStatusText(item.status) }}
              </el-tag>
            </div>

            <!-- 信息 -->
            <div class="item-info" @click="handleViewDetail(item)">
              <h3 class="item-title">{{ item.title }}</h3>
              <div class="item-meta">
                <div class="meta-item">
                  <el-icon><Location /></el-icon>
                  <span>{{ item.location }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatTime(item.foundTime) }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Folder /></el-icon>
                  <span>{{ item.category }}</span>
                </div>
              </div>

              <!-- 统计信息 -->
              <div class="item-stats">
                <span class="stat-item">
                  <el-icon><View /></el-icon>
                  {{ item.viewCount }}
                </span>
                <span class="stat-item">
                  <el-icon :class="{ liked: item.isLiked }">
                    <component :is="item.isLiked ? 'StarFilled' : 'Star'" />
                  </el-icon>
                  {{ item.likeCount }}
                </span>
                <span class="stat-item">
                  <el-icon><ChatDotRound /></el-icon>
                  {{ item.commentCount }}
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pagination"
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 详情对话框 -->
    <ItemDetailDialog
      v-model="detailVisible"
      :item-id="currentItemId"
      @refresh="handleDetailRefresh"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Location,
  Clock,
  Folder,
  View,
  Star,
  StarFilled,
  ChatDotRound,
  Picture
} from '@element-plus/icons-vue'
import { reqLostItemList, reqGetPendingClaims, reqAuditClaim } from '@/api/lost'
import type { LostItem, LostItemQueryParams } from '@/api/lost/type'
import ItemDetailDialog from './components/ItemDetailDialog.vue'
import dayjs from 'dayjs'
import userStore from '@/stores/modules/user'

const useUserStore = userStore()

// 判断是否为管理员
const isAdmin = computed(() => {
  return useUserStore.buttons.includes('lost:audit')
})

// 待审核申领列表
const pendingClaims = ref<any[]>([])
const auditTotal = ref(0)
const auditPage = ref(1)
const auditPageSize = ref(10)
const auditLoading = ref(false)

// 查询参数
const queryParams = reactive<LostItemQueryParams>({
  page: 1,
  pageSize: 12,
  keyword: '',
  category: '',
  status: undefined
})

// 失物列表
const lostItemList = ref<LostItem[]>([])
const total = ref(0)
const loading = ref(false)

// 详情对话框
const detailVisible = ref(false)
const currentItemId = ref(0)
const needRefresh = ref(false)

// 获取失物列表
const getLostItemList = async () => {
  // 防止重复请求
  if (loading.value) return
  
  loading.value = true
  try {
    const result = await reqLostItemList(queryParams)
    if (result.code === 200) {
      lostItemList.value = result.data.records
      total.value = result.data.total
    } else {
      ElMessage.error(result.message || '获取失物列表失败')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取失物列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getLostItemList()
}

// 重置
const handleReset = () => {
  queryParams.keyword = ''
  queryParams.category = ''
  queryParams.status = undefined
  handleSearch()
}

// 处理页码变化
const handlePageChange = () => {
  getLostItemList()
}

// 处理每页条数变化
const handleSizeChange = () => {
  queryParams.page = 1
  getLostItemList()
}

// 查看详情
const handleViewDetail = (item: LostItem) => {
  currentItemId.value = item.id
  detailVisible.value = true
  needRefresh.value = false
}

// 处理详情对话框的刷新请求
const handleDetailRefresh = () => {
  needRefresh.value = true
}

// 监听对话框关闭，如果需要刷新则刷新列表
watch(detailVisible, (newVal) => {
  if (!newVal && needRefresh.value) {
    getLostItemList()
    needRefresh.value = false
  }
})

// 获取状态类型
const getStatusType = (status: number) => {
  const types: Record<number, any> = {
    0: 'success',
    1: 'warning',
    2: 'info'
  }
  return types[status] || ''
}

// 获取状态文本
const getStatusText = (status: number) => {
  const texts: Record<number, string> = {
    0: '待认领',
    1: '已申领',
    2: '已归还'
  }
  return texts[status] || '未知'
}

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('MM-DD HH:mm')
}

// 页面加载时获取列表
// 获取待审核申领列表
const loadPendingClaims = async () => {
  if (auditLoading.value) return
  
  auditLoading.value = true
  try {
    const result = await reqGetPendingClaims({
      page: auditPage.value,
      pageSize: auditPageSize.value
    })
    if (result.code === 200) {
      pendingClaims.value = result.data.records
      auditTotal.value = result.data.total
    } else {
      ElMessage.error(result.message || '获取待审核申领失败')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取待审核申领失败')
  } finally {
    auditLoading.value = false
  }
}

// 审核通过
const handleAudit = async (claimId: number, status: number) => {
  try {
    const result = await reqAuditClaim({
      claimId,
      status,
      auditReason: ''
    })
    if (result.code === 200) {
      ElMessage.success('审核成功')
      loadPendingClaims()
      getLostItemList() // 刷新失物列表
    } else {
      ElMessage.error(result.message || '审核失败')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '审核失败')
  }
}

// 审核驳回
const handleReject = (claimId: number) => {
  ElMessageBox.prompt('请输入驳回原因', '驳回申领', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '请输入驳回原因'
  }).then(async ({ value }) => {
    try {
      const result = await reqAuditClaim({
        claimId,
        status: 2,
        auditReason: value
      })
      if (result.code === 200) {
        ElMessage.success('已驳回')
        loadPendingClaims()
        getLostItemList() // 刷新失物列表
      } else {
        ElMessage.error(result.message || '操作失败')
      }
    } catch (error: any) {
      ElMessage.error(error.message || '操作失败')
    }
  }).catch(() => {
    // 取消操作
  })
}

onMounted(() => {
  getLostItemList()
  if (isAdmin.value) {
    loadPendingClaims()
  }
})
</script>

<style scoped lang="scss">
.receive-container {
  padding: 20px;
}

.audit-card {
  margin-bottom: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  .audit-list {
    margin-bottom: 20px;
  }

  .audit-item {
    padding: 20px;
    margin-bottom: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: all 0.3s;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

    &:hover {
      background-color: #f5f7fa;
      border-color: #409eff;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
      transform: translateY(-2px);
    }

    &:last-child {
      margin-bottom: 0;
    }

    .audit-info {
      flex: 1;

      .item-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 8px;
      }

      .item-meta {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 8px;

        .location {
          color: #606266;
          font-size: 14px;
        }
      }

      .claim-info {
        color: #606266;
        font-size: 14px;
        margin-bottom: 8px;

        .divider {
          margin: 0 8px;
          color: #dcdfe6;
        }
      }

      .claim-reason {
        color: #909399;
        font-size: 14px;
      }
    }

    .audit-actions {
      display: flex;
      gap: 10px;
      margin-left: 20px;
    }
  }
}

.search-card {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 0;
  }
}

.list-container {
  min-height: 400px;
}

.item-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  }

  :deep(.el-card__body) {
    padding: 0;
  }
}

.item-image {
  position: relative;
  height: 200px;
  overflow: hidden;

  .el-image {
    width: 100%;
    height: 100%;
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;

    .el-icon {
      font-size: 48px;
    }
  }

  .status-tag {
    position: absolute;
    top: 10px;
    right: 10px;
  }
}

.item-info {
  padding: 15px;
}

.item-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 12px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #303133;
}

.item-meta {
  margin-bottom: 12px;

  .meta-item {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 13px;
    color: #606266;
    margin-bottom: 6px;

    .el-icon {
      font-size: 14px;
      color: #909399;
    }

    span {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

.item-stats {
  display: flex;
  gap: 15px;
  padding-top: 12px;
  border-top: 1px solid #ebeef5;

  .stat-item {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 13px;
    color: #909399;

    .el-icon {
      font-size: 16px;

      &.liked {
        color: #f56c6c;
      }
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

// 响应式设计
@media (max-width: 768px) {
  .receive-container {
    padding: 10px;
  }

  .search-form {
    :deep(.el-form-item) {
      display: block;
      margin-bottom: 10px;

      .el-form-item__content {
        margin-left: 0 !important;
      }
    }
  }

  .item-image {
    height: 180px;
  }
}
</style>
